<!--下载导入模板 上传短信模板-->
<template>
  <div class="si-add-template">
  <h2>{{$t('customer.changeLogType.import')}}</h2>
    <div class="wrap">
      <div class="btn-wrap">
        <el-button class="temp-download">
          <a :href="(lang === 'zh_CN' || lang === 'zh_TW') ? '/static/template/customer_template_zh.xlsx' : '/static/template/customer_template_en.xlsx'" download>{{$t('config.customer.downLoadCustomerTempl')}}</a>
        </el-button>
        <!--饿了么上传组件-->
        <el-upload
          class="temp-upload"
          :action="uploadUrl"
          name="upload"
          accept=".xls,.xlsx"
          :data="uploadHeaders"
          :with-credentials="true"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          :show-file-list="false">
          <el-button size="small" type="primary primary_btn">{{$t('config.customer.impCustomerTempl')}}</el-button>
        </el-upload>
      </div>
      <div v-if="isShow" class="import-templ">
        <el-button class="temp-download primary_btn" @click.stop="submitImport()" style="margin-bottom: 8px">
          {{$t('config.customer.import')}}
      </el-button>
        <el-form :inline="true" label-position="top"  class="">
        <el-row>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('config.customer.customerDb')">
                <el-select v-model="customerDb" :placeholder="$t('public.pleasePick')">
                  <el-option
                    v-for="item in customerDbs"
                    :key="item._id"
                    :label="item.name"
                    :value="item._id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('config.customer.customerStatus')">
                <el-select v-model="customerStatus" :placeholder="$t('public.pleasePick')">
                  <el-option
                    v-for="(item, key) in custTmpls.status"
                    :key="key"
                    :label="item"
                    :value="key">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('config.customer.dataSource')">
                <el-select v-model="customerSource" :placeholder="$t('public.pleasePick')">
                  <el-option
                    v-for="item in custTmpls.source"
                    :key="item.key"
                    :label="item.name"
                    :value="item.key">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('customer.importBatch')">
              <el-input v-model.trim="batchNo" :placeholder="$t('config.customer.writeCustomName')" :disabled="true" style="width: 200px"></el-input>
              <el-input v-model.trim="beizhu" :placeholder="$t('configLazyLoad.customerConfig.addTip')" style="width: 200px; padding-left: 10px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('configLazyLoad.customerConfig.tip1')">
                <el-radio class="radio" v-model="owner" :label="true">{{$t('public.myself')}}</el-radio>
                <el-radio class="radio" v-model="owner" :label="false">{{$t('customer.noOwner')}}</el-radio>
              </el-form-item>
            </el-col>
          <el-col :span="24" class="padd-b-10">
            <el-form-item :label="$t('configLazyLoad.customerConfig.customerExist')">
              <el-radio class="radio" v-model="customerExist" label="noImport">{{$t('km.kmSkip')}}</el-radio>
              <el-radio class="radio" v-model="customerExist" label="update">{{$t('customer.updateCustomer')}}</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
            <div class="padd-b-10 contact">{{$t('configLazyLoad.customerConfig.chooseRelevance')}}</div>
              <el-col :span="6" v-for="(item, index) in heads" :key="index" class="padd-b-10">
                <el-form-item :label="item.name">
                  <el-select v-model="item.value" :placeholder="$t('public.pleasePick')">
                    <el-option
                      v-for="(data, index) in customerFields"
                      :key="index"
                      :label="data.value"
                      :value="data.name">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
      </div>
      <div class="instructions">
        <p v-html="$t('config.customer.importInstructions')"></p>
        <div class="img-wrap">
          <!--<img src="../img/sms_template_import_eg.png" alt="">-->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { getDateNo } from '@/utils/m7Utils.js'
  export default {
    name: 'customerImportAddTemplate',
    data () {
      return {
        custom_fields: [],
        trueName: '',
        fileName: '',
        isShow: false,
        beizhu: '',
        custTmpls: {
          status: {},
          source: []
        },
        heads: [],
        customerSource: '',
        customerDbs: [],
        customerDb: '',
        customerStatus: '',
        customerFields: [],
        owner: true,
        customerExist: 'noImport',
        batchNo: '',
        uploadUrl: '/fileUpload',
        uploadHeaders: {
          type: '',
          module: 'customer',
          sessionId: this.$store.state.session.sessionId
        }
      }
    },
    computed: {
      lang() {
        return window.localStorage.lang || 'zh_CN'
      }
    },
    methods: {
      submitImport () {
        let heads = []
        let name = 'name'
        this.heads.forEach((item) => {
//          if (item.value) {
//            heads.push(item.value)
//          }
          heads.push(item.value)
        })
        if (heads.toString().indexOf(name) === -1) {
          this.$message.error(this.$t('config.customer.importContainCustomerName'))
          return false
        }
        this.owner = this.owner ? 'me' : ''
        let data = {
          customerExist: this.customerExist,
          fileName: this.fileName,
          trueName: this.trueName,
          dbType: this.customerDb,
          status: this.customerStatus,
          source1: this.customerSource,
          owner: this.owner,
          batchNo: this.batchNo + this.beizhu,
          heads,
          dic: {},
          flag: 'start'
        }
        let p1 = this.$store.dispatch('submitImport', data)
        Promise.all([p1]).then(([resp1]) => {
          console.log(resp1)
          let p2 = this.$store.dispatch('getImpTask', {_id: resp1.row._id}).then((resp) => {
            console.log(resp)
            let refreshLeft = {
              batchNo: resp.row.batchNo,
              flag: 'ImportFinish'
            }
            this.$store.commit('config/customer/REFRESH_LEFT', refreshLeft)
          })
          console.log(p2)
//          Promise.all(p2).then(() => {
//            this.$store.dispatch('getImpTask', {_id: id}).then((resp) => {
//              id = resp
//            })
//          })
        })
      },
//        上传前 配置上传参数
      beforeUpload (file) {
        let arr = file.name.split('.')
        let arrType = ['xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          return true
        } else {
          this.$message.error(this.$t('sms.uploadFileWrong'))
          return false
        }
      },
//      上传成功
      handleSuccess (response, file, fileList) {
        let fileName = response.filePath.split('/')
        this.trueName = response.fileName
        this.fileName = fileName[fileName.length - 1]
        this.$store.dispatch('getXlsHeads', {trueName: response.fileName, fileName: fileName[fileName.length - 1]}).then((resp) => {
          this.isShow = true
          this.heads = []
          console.log(resp.heads)
          resp.heads.forEach((item) => {
            let obj = {
              name: item,
              value: ''
            }
            this.customerFields.forEach(item1 => {
              if (item1.value === item) {
                obj.value = item1.name
              }
            })
            this.heads.push(obj)
          })
        })
      }
    },
    beforeMount () {
      this.custTmpls = this.$getCache('custTmpls')[0]
      let customerTmpl = this.custTmpls.stable_fields
      this.custTmpls.custom_fields.forEach((item) => {
        console.log(item)
        if (!item.status || item.status !== 'stop') {
          let obj = {
            name: item._id,
            value: item.name,
            required: item.required,
            noupdate: item.noupdate
          }
          this.custom_fields.push(obj)
        }
      })
      console.log(this.custTmpls)
      this.customerDbs.push({name: this.custTmpls.name, _id: this.custTmpls._id})
      this.customerDb = this.customerDbs[0]._id
      if (this.custTmpls.source.length !== 0) {
        this.customerSource = this.custTmpls.source[0].key
      } else {
        this.customerSource = ''
      }
      this.customerStatus = 'status0'
      this.batchNo = getDateNo()
      this.customerFields = this.customerFields.concat(customerTmpl, this.custom_fields)
      let _array = [
        {
          name: 'owner',
          value: this.$t('customer.customerOwner')
        },
        {
          name: 'custsource1',
          value: this.$t('customer.dataSource')
        },
        {
          name: 'status',
          value: this.$t('customer.custStatus')
        }
      ]
      this.customerFields = this.customerFields.concat(_array)
      console.log(this.customerFields)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  /*@import "src/assets/common.styl"*/
  .contact
    font-weight 500
    font-size 14px
  .si-add-template
    margin-left 341px
    height calc(100vh - 116px)
    padding-bottom 20px
    h2
      line-height 49px
      padding-left 20px
      font-size 14px
      color $cf-gray1
      border-bottom 1px solid #d9d9d9
    .import-templ
      .padd-b-10
        padding-bottom 10px
    .el-tabs__nav
      line-height 59px
    .wrap
      height calc(100vh - 220px)
      overflow auto
      padding 20px
      .btn-wrap
        padding-bottom 10px
        overflow hidden
        .temp-download
          float left
          background-color $c-sub
          border 1px solid $c-sub
          font-size 12px
          padding 8px
          a
            color #fff
        .temp-upload
          float left
          display inline-block
          margin-left 20px
          .temp-upload-btn
            background-color $c-main
            border 1px solid $c-main
            color #fff
            font-size 12px
            padding 7px
      .instructions
        margin-top 10px
        clear both
        font-size 12px
        line-height 22px
        color $c-prompt
      .img-wrap
        text-align center
</style>
